package com.chinaisafe.common.sdk.util;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import lombok.extern.slf4j.Slf4j;

/**
 * AesUtil
 * Description：AES加密工具
 *
 * @author xuefu.shu
 * @date  2024-07-16 13:04:27
 */
@Slf4j
public class AesUtil {

    //    长度只能是16位，24位，32位
    private static final String defaultKey = "Y2hpbmFpc2FmZQ==";

    /**
     * 加密
     * @param content 加密内容
     * @param key 加密秘钥
     * @return String
     * @author xuefu.shu
     * @date 2024-07-16 13:30
     */
    public static String encryptHex(String content, String key) {
        try {
            byte[] byteKey = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), key.getBytes()).getEncoded();
            //构建
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, byteKey);
            //加密
            return aes.encryptHex(content);
        } catch (Exception e) {
            log.error(" 加密异常:{}", e.getMessage());
        }
        return null;
    }

    /**
     * 解密
     * @param encryptString
     * @param key
     * @return String
     * @author xuefu.shu
     * @date 2024-07-16 13:30
     */
    public static String decryptStr(String encryptString, String key) {
        try {
            byte[] byteKey = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(),
                    key.getBytes()).getEncoded();
            SymmetricCrypto aes = SecureUtil.aes(byteKey);
            //解密
            return aes.decryptStr(encryptString);
        } catch (Exception e) {
            log.error(" 解密异常:{}", e.getMessage());
        }
        return null;
    }


    public static void main(String[] args) {
        // 16位自定义密码
        String content = "123456";
        String encryptStr = encryptHex(content, defaultKey);
        System.out.println(encryptStr);
        System.out.println(decryptStr(encryptStr, defaultKey));
    }
}
